from google.appengine.dist import use_library 
use_library('django', '1.2')


from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from models.main import *
from models.schema import *
import os
import urllib2
from google.appengine.ext.webapp import template
from google.appengine.ext import db
import random
from django.core.paginator import Paginator, InvalidPage
from google.appengine.ext import webapp
from modules.node.module import Module as NodeModule

from s5lib.Paginator import *

M.pathes['templates'] = os.path.join(os.path.dirname(__file__), 'templates')
M.urls['base'] = 'http://localhost:8080/'

class MainHandler(webapp.RequestHandler):
    def get(self):
		values = {
			'message': 'hi',
			'short_url': 'Short URl'
		}
		self.response.out.write(M.theme('index', values))
		
class ListUrlsHandler(webapp.RequestHandler):
    def get(self, current_page):
		if current_page == "":
			current_page = 0
		current_page = int(current_page) - 1
		query = db.Query(ShortenUrl)
		url = M.urls['base'] + "list_urls/%d"
		on_page = 10
		results = query.fetch(on_page)
		values = {
			'list': query.fetch(on_page),
			'paginator': render_paginator(query, 4, url)
		}
		values['count'] = query.count()
		values['list'] = results
		 # Show 25 contacts per page
		self.response.out.write(M.theme('list_urls', values))
		
class UrlHandler(webapp.RequestHandler):
    def post(self):
		messages = []
		url = self.request.get('url')
		values = {
			'messages': "",
			'url': url,
			'short_url': ''
		}
		if not M.check_url(values['url']):
			messages.append('Invalid URL')
			values['messages'] = M.theme('messages', {'messages': messages})
			self.response.out.write(M.theme('index', values))
			return
		db_url = ShortenUrl.get_or_insert(url)
		if (db_url.new == False):
			messages.append('The short url for this long url has ben already generated before.')
		else:
			messages.append('A new short link was generated.')
		id = db_url.key().id()
		coder = S5Code()
		code = coder.IntToCode(id)
		values['shorten_url'] = '%ss/%s' % (M.urls['base'], code)
		if len(messages) > 0:
			values['messages'] = M.theme('messages', {'messages': messages})
		self.response.out.write(M.theme('index', values))
		return
		
class GenerateHandler(webapp.RequestHandler):
	def get(self, count):
		answer = ''
		prefix = 'http://www.vkontakte.ru/id%d'
		for x in range(int(count)):
			r = random.randint(1, 100)
			db_url = ShortenUrl.get_or_insert(prefix % r)
			answer += '%s - %d<br>' % (db_url.long_url, db_url.refferals)
		self.response.out.write(answer)
		pass
		
class RedirectHandler(webapp.RequestHandler):
	def get(self, code):
		coder = S5Code()
		id = coder.CodeToInt(code)
		db_url = ShortenUrl.get_by_id(id)
		db_url.refferals += 1
		db_url.put()
		self.redirect(db_url.long_url)
		return
		
def main():
	urls = [
		('/', MainHandler),
		('/url', UrlHandler),
		(r'/s/(.*)', RedirectHandler),
		(r'/generate/(.*)', GenerateHandler),
		(r'/list_urls/(.*)', ListUrlsHandler),
	]
	node_module = NodeModule()
	urls.extend(node_module.urls)
	application = webapp.WSGIApplication(urls, debug=True)
	util.run_wsgi_app(application)

if __name__ == '__main__':
    main()
